var globalCount = 0;
$("#fakeloader").fakeLoader({
	timeToHide : 10000, //Time in milliseconds for fakeLoader disappear
	zIndex : 999, // Default zIndex
	spinner : "spinner6", //Options: 'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7' 
	bgColor : "#fff", //Hex, RGB or RGBA colors
});
setTimeout(function() {
	$('body').css('opacity', '1');
	$('body').attr("class", "gray-bg") //添加样式
}, 100);

$(document).ready(function() {
	selectMessage();
});

var returnAllCount = function() {
	if (globalCount == 1) {
		setTimeout(function() {
			$('#fakeloader').css('display', 'none');
		}, 500);
	}
}
//初始化表格数据
var selectMessage = function() {
	$('#allBlog').bootstrapTable({
		method : 'post',
		url : "../selectAllMessage",
		dataType : "json",
		striped : false, //使表格带有条纹  
		pagination : true, //在表格底部显示分页工具栏  
		pageSize : 10,
		pageNumber : 1,
		sortStable : true,
		sortable : true,
		pageList : [ 10, 20, 50, 100 ],
		idField : "id", //标识哪个字段为id主键  
		showToggle : false, //名片格式  
		cardView : false, //设置为True时显示名片（card）布局  
		showColumns : true, //显示隐藏列    
		showRefresh : true, //显示刷新按钮  
		//singleSelect: true,//复选框只能选择一条记录  
		search : true, //是否显示搜索框
		searchOnEnterKey : true, //设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
		//clickToSelect: true,//点击行即可选中单选/复选框  
		queryParams : queryParams, //参数  
		showFullscreen:true,  //全屏按钮
		//queryParamsType: "limit", //查询参数组织方式
		sidePagination : "server", //服务端处理分页
		silent : true, //刷新事件必须设置  
		searchTimeOut : 500, //设置搜索超时时间
		toolbarAlign : 'left', //工具栏对齐方式
		buttonsAlign : 'right', //按钮对齐方式
		toolbar : '#toolbar', //指定工作栏
		searchAlign : 'right',
		// singleSelect : true,
		contentType : "application/x-www-form-urlencoded",
		formatLoadingMessage : function() {
			
			return "请稍后，正在加载中...";
		},
		formatNoMatches : function(res) { //没有匹配的结果  
			return "无符合条件的记录/您没有查看权限";
		},
		responseHandler : function(res) {
			console.log(res);
			if(res=="201"){
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
				return {
					"total" : 0, //总页数
					"rows" : null //数据
				};
			}
			return {
				"total" : res.pageInfo.total, //总页数
				"rows" : res.pageInfo.list //数据
			};
		},
		columns : [
			{
				checkbox : true,
				width : '3%',
				align : 'center',
				valign : 'middle',
			},
			{
				title : '序号',
				align : 'center',
				valign : 'middle',
				width : '4%',
				formatter : function(value, row, index) {
					var index1 = index + 1;
					var id = '<span title="ID:' + row.id + '">' + index1 + '</span>';
					return id;
				}
			},
			{
				title : 'ip',
				field : 'ip',
				align : 'center',
				valign : 'middle',
				width : '8%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},
			{
				title : '内容',
				field : 'content',
				align : 'center',
				width : '19%',
				cellStyle : formatTableUnit,
				formatter : operateOpinionFormatter
			},
			{
				title : '类型',
				field : 'type',
				align : 'center',
				width : '6%',
				formatter : function(value, row, index) {
					if (row.type == 1) {
						return '<button class="btn-xs btn-primary">普通消息</button>';
					} else if (row.type == 2) {
						return '<button class="btn-xs btn-info">待定</button>';
					} 
				}
			},

			{
				title : '状态',
				field : 'status',
				align : 'center',
				width : '6%',
				formatter : function(value, row, index) {
					if (row.status == 1) {
						return '<button class="btn-xs btn-danger">未读</button>';
					} else if (row.status == 2) {
						return '<button class="btn-xs btn-info">已读</button>';
					} 
				}
			},
			{
				title : '发送日期',
				field : 'createDate',
				align : 'center',
				width : '15%',
				formatter : function(value, row, index) {
					return Format(row.createDate, "yyyy-MM-dd hh:mm:ss");
				}
			},
			{
				title : '操作',
				field : 'id',
				align : 'center',
				width : '15%',
				formatter : function(value, row, index) {
					//修改用户	
					var a = '<a  class=" btn-sm btn-info"  onclick="operation(' + row.id + ',\'设为已读\')"><i class="fa fa-eye" ></i> 设为已读</a> ';
					//删除用户
					var c = '<a  class=" btn-sm btn-danger"  onclick="delMessage(' + row.id + ',\'删除\')"><i class="fa fa-remove" ></i> 删除</a> ';
					if(row.status==1){
						return a+c;
					}else{
						return c;
					}
						
				}
			}
		]
	});
	globalCount++;
	returnAllCount();
}

//传参数到后台
function queryParams(params) {
	return {
		pageSize : params.limit,
		page : (params.offset) / params.limit + 1,
		ip : $(".form-control").val(),
		content : $(".form-control").val(),
		status : ''
	}
}

//设置 字数不超过宽度限制
var operateOpinionFormatter = function(value, row, index) {
	var title = "";
	var content = $(".form-control").val();
	var contentLow = $(".form-control").val().toLowerCase();
	var strStartIndex = '';
	var strEndIndex = '';
	if (value.search(content) != -1 || value.toLowerCase().search(contentLow) != -1) {
		var strs = new Array();
		strs = value.split("");
		strStartIndex = value.indexOf(content);
		strEndIndex = strStartIndex + content.length - 1;
		if (value.toLowerCase().search(contentLow) != -1) {
			strStartIndex = value.toLowerCase().indexOf(contentLow);
			strEndIndex = strStartIndex + contentLow.length - 1;
		}
		for (var i = 0; i < strs.length; i++) {
			if (i >= strStartIndex && i <= strEndIndex) {
				title += '<span style="color:#000;font-weight:bold;">' + strs[i] + '</span>';
			} else {
				title += '<span >' + strs[i] + '</span>';
			}
		}
	} else {
		title = value;
	}
	if (value.length > 15) {
		var num = strEndIndex - strStartIndex;
		var index = strStartIndex - 4;
		if (index < 0) {
			index = 0;
		}
		if (content == "") {
			return "<span title='" + value + "'>" + title.substring(0, 150) + "..." + "</span>";
		} else {
			return "<span title='" + value + "'>" + title.substring(15 * index, (15 * index) + (num + 1) * 51 + (9 - num) * 15) + "..." + "</span>";
		}
	} else {
		return "<span  title='" + value + "'>" + title.substring(0, title.length) + "</span>";
	}
}

var formatTableUnit = function(value, row, index) {
	return {
		css : {
			"overflow" : 'hidden',
			"text-overflow" : 'ellipsis',
			"white-space" : 'nowrap'
		}
	};
}
//未处理友链和消息
/*var initNoApplyLinksCount = function() {
	$.ajax({
				url : '../admin/selectNoApplyLinksCount',
				type : 'post',
				data : '',
				dataType : 'json',
				success : function(data) {
					var count = '';
					var isApplyLinks = '';
					var messages = '';
					var isMessages = '';
					if (data.status == 200) {
						if(data.mcount>0){
							messages = '<span class="label label-danger pull-right">'
								+ data.mcount + '</span>';
						}
						if(data.count>0){
							count = '<span class="label label-danger pull-right">'
									+ data.count + '</span>';
						}
					} else {
						count = '<span class="fa arrow"></span>';
						messages = '<span class="fa arrow"></span>';
					}
					$(".links").append(count);
					$(".isApplyLinks").find('a').append(count);
					$(".messages").append(messages);
					$(".isMessages").find('a').append(messages);
				},
				error : function() {
				}
			});
}*/
//删除消息
var delMessage = function(id){
	param = { 
			id : id
	}
	$.ajax({
		url : '../deleteMessage',
		type : 'post',
		data : param,
		dataType : 'json',
		success : function(data) {
			//查询成功
			if (data.status == 200) {
				$("#allBlog").bootstrapTable('refresh');
				//initNoApplyLinksCount();
				swal("删除成功", "", "success");
			} else if(data=="201") {
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
			}else{
				swal("删除失败", "请重新操作", "error");
			}
		},
		error : function() {
			swal("删除错误", "请重新操作", "error");
		}
	});
}

//获取行号  
var getSelectRows = function() {
	var date = $("#allBlog").bootstrapTable('getSelections');
	var idArray = new Array();
	var title = '';
	var text = '';
	if(date.length<1){
		swal("请选择需要操作的消息", "", "warning","22em");
		return false;
	}
		title = '确定要删除这' + date.length + '条消息吗';
		text = '删除后将无法恢复，请谨慎操作！';
	swal({
		title : title,
		text : text,
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#DD6B55",
		confirmButtonText : "确定",
		closeOnConfirm : false
	}, function() {
		console.log(date);
				for (var i = 0; i < date.length; i++) {
					idArray[i] = date[i].id;
					delMessage(idArray[i]); 
				}
		})
};

var operation = function(id, op) {
	var title = "";
	var text = "";
	if (op == "删除") {
		title = '确定要删除吗';
		text = '删除后,无法恢复谨慎操作';
		swal({
			title : title,
			text : text,
			type : "warning",
			showCancelButton : true,
			confirmButtonColor : "#DD6B55",
			confirmButtonText : "确定",
			closeOnConfirm : false
		}, function() {
			if (op == "删除") {
				delMessage(id);
			}
		});
	} else if (op == "设为已读") {
		operationRole(id, 2, null, null);
	}
	
};

//消息的操作
var operationRole = function(idArray, status, sex, roleId) {
	var param = '';
	if (status != null) {
		param = {
			'id' : idArray,
			'status' : status,
		};
	}
	$.ajax({
		url : '../updateMessage',
		type : 'post',
		data : param,
		dataType : 'json',
		success : function(data) {
			//更新成功
			if (data.status == 200) {
				$("#allBlog").bootstrapTable('refresh');
				swal({title:"更新成功",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
				initNoApplyLinksCount();
			} else if(data=="201") {
				swal({title:"未授权",width:"100",height:"50px", text:"",showConfirmButton:false, type:"warning",timer:"1000"}); 
			}else{
				swal("更新失败", "请重新操作", "error");
			}
		},
		error : function() {
			swal("更新错误", "请重新操作", "error");
		}
	});
}


//格式化时间
function Format(datetime, fmt) {
	if (parseInt(datetime) == datetime) {
		if (datetime.length == 10) {
			datetime = parseInt(datetime) * 1000;
		} else if (datetime.length == 13) {
			datetime = parseInt(datetime);
		}
	}
	datetime = new Date(datetime);
	var o = {
		"M+" : datetime.getMonth() + 1, //月份   
		"d+" : datetime.getDate(), //日   
		"h+" : datetime.getHours(), //小时   
		"m+" : datetime.getMinutes(), //分   
		"s+" : datetime.getSeconds(), //秒   
		"q+" : Math.floor((datetime.getMonth() + 3) / 3), //季度   
		"S" : datetime.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
